﻿using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.AspNetCore.Identity;
using data.jianvgroup.com;
using data.jianvgroup.com.Entity;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;
using jianvgroup.com.Models.AccountViewModels;
using jianvgroup.com.Common;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace jianvgroup.com.Controllers
{
    public class AccountController : Controller
    {
        private readonly string _externalCookieScheme;
        private readonly JvgroupContext _db;
        private readonly UserManager<jvuser> _userManager;
        private readonly SignInManager<jvuser> _signInManager;
        private readonly ILogger<AccountController> _logger;
        private readonly RoleManager<IdentityRole> _roleManager;

        public AccountController(IOptions<IdentityCookieOptions> identityCookieOptions,
             JvgroupContext db,
            UserManager<jvuser> userManager,
            SignInManager<jvuser> signInManager,
            ILogger<AccountController> logger,
            RoleManager<IdentityRole> roleManager)
        {
            _externalCookieScheme = identityCookieOptions.Value.ExternalCookieAuthenticationScheme;
            _db = db;
            _userManager = userManager;
            _signInManager = signInManager;
            _logger = logger;
            _roleManager = roleManager;
        }

        [HttpGet]
        public async Task<IActionResult> Login(string returnUrl = null)
        {
            await HttpContext.Authentication.SignOutAsync(_externalCookieScheme);

            ViewBag.ReturnUrl = returnUrl;

            return View();
        }

        /// <summary>
        ///  确定登陆
        /// </summary>
        /// <param name="model">Login</param>
        /// <param name="returnUrl">返回连接</param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
        {
            try
            {
                ViewBag.ReturnUrl = returnUrl;
                if (ModelState.IsValid)
                {
                    var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, lockoutOnFailure: false);
                    //var user = await _userManager.FindByNameAsync(model.UserName);
                    //if (user != null)
                    //{
                    //    var roles = await _userManager.GetRolesAsync(user);
                    //    if (roles.Contains(Constant.INVESTORROLE))
                    //    {
                    //        ModelState.AddModelError(string.Empty, "非系统用户无法登陆!");
                    //        return View(model);
                    //    }
                    //}

                    if (result.Succeeded)
                    {
                        return RedirectToLocal(returnUrl);
                    }
                    else
                    {
                        ModelState.AddModelError(string.Empty, "用户或密码错误!");
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(500, ex.ToString(), "登陆异常", null);
                ModelState.AddModelError(string.Empty, "用户或密码错误!");
            }

            return View(model);
        }


        [HttpGet]
        public async Task<IActionResult> InitUser(string userName = "admin", string password = "Jv_123456")
        {
            if (ModelState.IsValid)
            {
                var user = new jvuser { UserName = userName, PasswordHash = password, Email = userName };
                var result = await _userManager.CreateAsync(user, password);
                var identityRole = new IdentityRole
                {
                    Name = Constant.SYSTEMROLE,
                };
                if (!await _roleManager.RoleExistsAsync(Constant.SYSTEMROLE))
                {
                    var addRolt = await _roleManager.CreateAsync(identityRole);
                    var roleResult = await _roleManager.FindByNameAsync(Constant.SYSTEMROLE);
                }
                var add = await _userManager.AddToRoleAsync(user, Constant.SYSTEMROLE);
                if (result.Succeeded)
                {
                    _logger.LogInformation(3, "User created a new account with password.");
                    return Content("OK");
                }
            }
            return Content("ERROR");
        }

        /// <summary>
        /// 注销
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> Logout()
        {
            await _signInManager.SignOutAsync();

            _logger.LogInformation(4, string.Format("{0}:user logout...", DateTime.Now));

            return RedirectToAction(nameof(AccountController.Login), "Account");
        }

        private void AddErrors(IdentityResult result)
        {
            foreach (var error in result.Errors)
            {
                ModelState.AddModelError(string.Empty, error.Description);
            }
        }

        private IActionResult RedirectToLocal(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction(nameof(HomeController.Index), "Home");
            }
        }
    }
}
